package algorithms.threadpool;


import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池+队列 处理发短信
 */
public class SendMes {
    private ScheduledThreadPoolExecutor executor;
    private Queue<String> queue;

    public SendMes() {
        this.executor = new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutor.CallerRunsPolicy());
        this.queue = new LinkedBlockingDeque<String>();

        //5s处理一次
        executor.scheduleAtFixedRate(() -> {
            execute();
        }, 0, 5, TimeUnit.SECONDS);
    }

    public void send(String mes) {
        queue.add(mes);
    }

    public void execute() {
        // 一次处理100条
        System.out.println("批次："+ UUID.randomUUID().toString());
        for (int i = 0; i < 10; i++) {
            String mes = queue.poll();
            if (mes != null) {
                System.out.println("发送消息==》" + mes);
            }
        }
        System.out.println("剩余数量："+ queue.size());
    }

}
